import Vue from "vue";
import VueRouter from "vue-router";
import home from "../views/Home.vue";
import login from "../components/login.vue";
import users from "../components/user/user.vue";
import reports from "../components/reports/reports.vue";
import Rights from "../components/power/Rights.vue";
import Roles from "../components/power/Roles.vue";
import Order from "../components/order/Order.vue";
// 商品管理
import Cate from "../components/goods/Cate.vue";
import Params from "../components/goods/Params.vue";
import GoodList from "../components/goods/List.vue";
import Add from "../components/goods/Add.vue";

Vue.use(VueRouter);

const routes = [
  { path: "/", redirect: "/login" },
  { path: "/login", component: login },
  {
    path: "/home",
    component: home,
    redirect: "/users",
    children: [
      { path: "/users", component: users },
      { path: "/reports", component: reports },
      { path: "/rights", component: Rights },
      { path: "/roles", component: Roles },
      { path: "/orders", component: Order },
      // 商品管理
      { path: "/categories", component: Cate },
      { path: "/params", component: Params },
      { path: "/goods", component: GoodList },
      { path: "/goods/add", component: Add },
    ],
  },
];

const router = new VueRouter({
  routes,
});

// 为路由对象，添加 beforeEach 导航守卫
router.beforeEach((to, from, next) => {

  //to 将要访问的路径
  //from代表从哪个路径跳转而来
  //next 是一个继承表示放行
  // next（）放行，next（'/login'）强制跳转

  // 如果用户访问的登录页，直接放行
  if (to.path == "/login") return next();
  // 从 sessionStorage获取 保存的 token 值
  const tokenStr = window.sessionStorage.getItem("token");
  // 没有 token 强制跳转到登录页
  if (!tokenStr) return next("/login");
  next();
});

export default router;
